package com.example.tobebigfe.jsbridge

import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import org.json.JSONObject

interface BridgeModule {
    fun callFunc(func: String, callbackId: String, arg: JSONObject)
}

abstract class BridgeModuleBase(val webView: WebView) : BridgeModule {

    fun callback(callbackId: String, value: Int) {
        execJS("window.$callbackId($value)")
    }

    fun callback(callbackId: String, value: Boolean) {
        execJS("window.$callbackId($value)")
    }

    fun callback(callbackId: String, value: String?) {
        if (value == null) {
            execJS("window.$callbackId(null)")
        } else {
            execJS("window.$callbackId('$value')")
        }
    }

    fun callback(callbackId: String, json: JSONObject) {
        execJS("window.$callbackId($json)")
    }

    fun execJS(script: String) {
        Log.e("WebView", "exec $script")
        webView.post {
            webView.evaluateJavascript(script, null)
        }
    }

}

class BridgeObject(val activity: WebActivity, val webView: WebView) {

    private val bridgeModuleMap = mutableMapOf<String, BridgeModule>()

    init {
        bridgeModuleMap["UI"] = JSBridgeUI(activity, webView)
        bridgeModuleMap["KVDB"] = JSBridgeKVDB(activity, webView)
        bridgeModuleMap["Camera"] = JSBridgeCamera(activity, webView)
        bridgeModuleMap["Image"] = JSBridgeImage(activity, webView)
    }

    @JavascriptInterface
    fun callNative(callbackId: String, method: String, arg: String) {
        Log.e("WebView", "callNative $method args is $arg")
        val jsonArg = JSONObject(arg)
        val split = method.split(".")
        val moduleName = split[0]
        val funcName = split[1]

        val module = bridgeModuleMap[moduleName]
        module?.callFunc(funcName, callbackId, jsonArg)
    }
}